package com.koron.order.experiment.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.koron.bean.base.Attachment;
import com.koron.bean.base.Response;
import com.koron.bean.system.staff.Constant;
import com.koron.bean.util.ServletUtils;
import com.koron.common.core.business.print.ReportTask;
import com.koron.common.core.business.print.bean.PrintTemplateBean;
import com.koron.common.core.business.print.bean.dto.PrintBusinessDto;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.FastJsonUtils;
import com.koron.order.common.bean.po.OrderInstructionBean;
import com.koron.order.common.bean.po.OrderSignBean;
import com.koron.order.common.controller.OrderExecuteController;
import com.koron.order.experiment.bean.dto.ExperimentExecuteDto;
import com.koron.order.experiment.bean.dto.FiledDescriptDto;
import com.koron.order.experiment.bean.po.*;
import com.koron.order.experiment.bean.vo.ExperimentEquipmentVo;
import com.koron.order.experiment.bean.vo.ExperimentItemVo;
import com.koron.order.experiment.bean.vo.OperateFormVo;
import com.koron.order.experiment.feign.PrintStandardFeignService;
import com.koron.order.experiment.service.ExperimentExecuteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ExperimentExcuteController
 * @description
 * @Author zhouj
 * @Date 2021/9/16 8:51
 */
@Api(tags = "试验工单-执行中信息")
@RestController
@RequestMapping("/experiment/execute/")
public class ExperimentExecuteController extends OrderExecuteController {

    @Autowired
    private ExperimentExecuteService experimentExecuteService;

    @Autowired
    PrintStandardFeignService printStandardFeignService;

    @ApiOperation(value = "新增或更新")
    @PostMapping("insertOrUpdate")
    public Response<Integer> insertOrUpdate(@RequestBody ExperimentExecuteDto dto) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "insertOrUpdate", Integer.class, dto));
    }

    @ApiOperation(value = "根据id删除 ")
    @DeleteMapping("deleteById")
    public Response<Integer> deleteById(String id) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "deleteById", Integer.class, id));
    }

    @ApiOperation(value = "根据工单Id查询作业表单信息 ")
    @GetMapping("queryByOrderId")
    public Response<OperateFormVo> queryByOrderId(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryByOrderId", OperateFormVo.class, orderId));
    }

    @ApiOperation(value = "根据工单Id查询作业表单-作业准备信息 ")
    @GetMapping("queryReadyByOrderId")
    public Response<List<ExperimentReadyPo>> queryReadyByOrderId(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryReadyByOrderId", List.class, orderId));
    }

    @ApiOperation(value = "根据工单Id查询作业表单-作业指导书信息 ")
    @GetMapping("queryInstructionByOrderId")
    public Response<List<OrderInstructionBean>> queryInstructionByOrderId(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryInstructionByOrderId", List.class, orderId));
    }

    @ApiOperation(value = "根据工单Id查询作业表单-设备以及下属项目列表信息 ")
    @GetMapping("queryEquipmentVoByOrderId")
    public Response<List<ExperimentEquipmentVo>> queryEquipmentVoByOrderId(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryEquipmentVoByOrderId", List.class, orderId));
    }

    @ApiOperation(value = "根据工单Id查询作业表单-设备信息列表信息 ")
    @GetMapping("queryEquipmentBeanListByOrderId")
    public Response<List<ExperimentEquipmentPo>> queryEquipmentBeanListByOrderId(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryEquipmentBeanListByOrderId", List.class, orderId));
    }

    @ApiOperation(value = "根据设备表Id查询作业表单-设备-环境,设备参数列表信息 ")
    @GetMapping("queryExperimentParamsByEqId")
    public Response<ExperimentEquipmentVo> queryExperimentParamsByEqId(String orderId, String experimentEquipId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryExperimentParamsByEqId", ExperimentEquipmentVo.class, orderId, experimentEquipId));
    }

    @ApiOperation(value = "根据工单Id,设备主表id查询作业表单-设备下项目信息列表信息 ")
    @GetMapping("queryExperimentItemByEqId")
    public Response<List<ExperimentItemVo>> queryExperimentItemByEqId(String orderId, String experimentEquipId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryExperimentItemByEqId", List.class, orderId, experimentEquipId));
    }

    @ApiOperation(value = "根据工单Id查询工单下已经签名完成的附件列表 ")
    @GetMapping("queryAttachmentListByOrderId")
    public Response<List<Attachment>> queryAttachmentListByOrderId(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "queryAttachmentListByOrderId", List.class, orderId));
    }

    @ApiOperation(value = "新增或更新作业表单信息")
    @PutMapping("insertOrUpdateOperateForm")
    public Response<String> insertOrUpdateOperateForm(@RequestBody OperateFormVo operateFormVo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "insertOrUpdateOperateForm", String.class, operateFormVo));
    }

    @ApiOperation(value = "更新作业表单-作业准备信息")
    @PutMapping("updateExperimentReady")
    public Response<Integer> updateExperimentReady(@RequestBody ExperimentReadyPo experimentReadyPo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentReady", Integer.class, experimentReadyPo));
    }

    @ApiOperation(value = "更新作业表单-作业过程信息")
    @PutMapping("updateExperimentItemVo")
    public Response<Integer> updateExperimentItemVo(@RequestBody ExperimentItemVo experimentItemVo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentItemVo", Integer.class, experimentItemVo));
    }

    @ApiOperation(value = "更新作业表单-作业过程-环境,设备参数信息")
    @PutMapping("updateExperimentParamsPo")
    public Response<Integer> updateExperimentParamsPo(@RequestBody ExperimentParamsPo paramsPo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentParamsPo", Integer.class, paramsPo));
    }

    @ApiOperation(value = "更新作业表单-作业过程-项目信息")
    @PutMapping("updateExperimentItem")
    public Response<Integer> updateExperimentItem(@RequestBody ExperimentItemPo experimentItemPo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentItem", Integer.class, experimentItemPo));
    }

    @ApiOperation(value = "更新作业表单-作业过程-参数项值信息")
    @PutMapping("updateExperimentItemParams")
    public Response<Integer> updateExperimentItemParams(@RequestBody ExperimentItemParamsPo itemParamsBean) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentItemParams", Integer.class, itemParamsBean));
    }

    @ApiOperation(value = "更新作业表单-作业过程-签名信息")
    @PutMapping("insertOrderSignInfo")
    public Response<Integer> insertOrderSignInfo(@RequestBody OrderSignBean orderSignBean) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "insertOrderSignInfo", Integer.class, orderSignBean));
    }

    @ApiOperation(value = "更新作业表单-作业表单-主表信息")
    @PutMapping("updateExperimentInfo")
    public Response<Integer> updateExperimentInfo(@RequestBody ExperimentPo experimentPo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentInfo", Integer.class, experimentPo));
    }

    @ApiOperation(value = "更新作业表单-作业表单-设备主表信息")
    @PutMapping("updateExperimentEquipmentInfo")
    public Response<Integer> updateExperimentEquipmentInfo(@RequestBody ExperimentEquipmentPo equipmentPo) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "updateExperimentEquipmentInfo", Integer.class, equipmentPo));
    }

    @ApiOperation(value = "作业标准生成项目及参数项列表")
    @PutMapping("generateStand")
    public Response<Boolean> generateStand(String orderId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "generateStand", Boolean.class, orderId));
    }

    @ApiOperation(value = "查询设备实验报告中数据")
    @GetMapping("getExperimentData")
    public Response<Map> getExperimentData(String experimentEquipmentId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "getExperimentData", Map.class, experimentEquipmentId));
    }

    @ApiOperation(value = "查询模板json通过试验设备id")
    @GetMapping("getExperimentDataJson")
    public Response<List<FiledDescriptDto>> getExperimentDataJson(String experimentEquipmentId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "getExperimentDataJson", List.class, experimentEquipmentId));
    }

    @ApiOperation(value = "查询模板json从标准查询")
    @GetMapping("getExperimentDataJsonFromStandard")
    public Response<List<FiledDescriptDto>> getExperimentDataJsonFromStandard(String standardId) {
        return Response.ok(ADOConnection.runTask(getCurrDs(), experimentExecuteService, "getExperimentDataJsonFromStandard", List.class, standardId));
    }

    @ApiOperation(value = "设计试验报告")
    @GetMapping("getPrintTemplate")
    public Response<Object> getPrintTemplate(@RequestParam String standardId,@RequestParam String standardName) {
        List list = ADOConnection.runTask(getCurrDs(), experimentExecuteService, "getExperimentDataJsonFromStandard", List.class, standardId);
        String beanToJson = FastJsonUtils.getBeanToJson(list);

        //构造公共模块  调起设计接口,返回链接给前端
        PrintBusinessDto printBusinessDto = new PrintBusinessDto();
        printBusinessDto.setCode(standardId);
        printBusinessDto.setName(standardName);
        printBusinessDto.setField(beanToJson);

        return printStandardFeignService.directDesign(printBusinessDto);

    }

    /**
     * 生成实验报告
     *
     * @return
     */
    @ApiOperation(value = "预览实验报告 (需要先 安装 打印控件)")
    @SuppressWarnings("unchecked")
    @GetMapping("/previewExperiment.htm")
    public Response<String> previewExperiment(@RequestParam String standardId) {

        //先根据标准id查询模板id
        Response<Object> response = printStandardFeignService.readPrintBusListByBusinessCode(standardId);
        Object data = response.getData();

        String s = JSON.toJSONString(data);
        // 将这个Json字符串转换成一个List集合。
        List<PrintTemplateBean> list = JSONObject.parseArray(s, PrintTemplateBean.class);

        Assert.notEmpty(list,"找不到模板");
        //一个标准对应一个模板
        PrintTemplateBean printTemplateBean = list.get(0);
        String printTemplateId = printTemplateBean.getId();

        Response<List<FiledDescriptDto>> experimentDataJsonFromStandard = getExperimentDataJsonFromStandard(standardId);
        List<FiledDescriptDto> filedDescriptDtos = experimentDataJsonFromStandard.getData();

        String url = ReportTask.printData(printTemplateId, filedDescriptDtos);//没有预览数据，以及返回打印地址

        return Response.ok("获取成功，拿返回地址回调打印", url);
    }

    /**
     * 生成实验报告
     *
     * @return
     */
    @ApiOperation(value = "打印实验报告 (需要先 安装 打印控件)")
    @SuppressWarnings("unchecked")
    @GetMapping("/printExperiment.htm")
    public Response<String> printExperiment(String experimentEquipmentId, String standardId) {

        //根据experimentEquipmentId查找实验报告模板(该模板大致为单个设备--多个项目,多参数值)
        List<Object> list = new ArrayList<>();
        list.add(getExperimentData(experimentEquipmentId).getData());

        //先根据标准id查询模板id
        //由于是从系统库查找模板,所以需要提前设置好请求头参数,方便feign解析
        HttpServletRequest request = ServletUtils.getRequest();
        request.setAttribute(Constant.DYNAMIC_DATA_SOURCE,"_default");

        Response<Object> response = printStandardFeignService.readPrintBusListByBusinessCode(standardId);
        Object data = response.getData();

        String s = JSON.toJSONString(data);
        // 将这个Json字符串转换成一个List集合。
        List<PrintTemplateBean> printTemplateBeans = JSONObject.parseArray(s, PrintTemplateBean.class);

        Assert.notEmpty(printTemplateBeans,"找不到模板");
        //一个标准对应一个模板
        PrintTemplateBean printTemplateBean = printTemplateBeans.get(0);
        String printTemplateId = printTemplateBean.getId();

        ThreadLocalContext.get().setCurrDs("_default");
        String url = ReportTask.printData(printTemplateId, list);//存储打印数据，以及返回打印地址

        return Response.ok("获取成功，拿返回地址回调打印", url);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "experimentEquipmentId", value = "试验设备表id", dataType = "String"),
            @ApiImplicitParam(name = "tenantName", value = "签名方名称", required = true, dataType = "String"),
            @ApiImplicitParam(name = "contact", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "type", value = "事件类型", required = true, dataType = "String"),
            @ApiImplicitParam(name = "signStatus", value = "签名状态", required = true, dataType = "String")
    })
    @GetMapping("electronicSignatureCallback")
    @ApiOperation("电子签章-签名回调接口")
    public Response electronicSignatureCallback(@RequestParam("experimentEquipmentId") String experimentEquipmentId,
                                                @RequestParam("documentId") String documentId,
                                                @RequestParam("tenantName") String tenantName,
                                                @RequestParam("contact") String contact,
                                                @RequestParam("type") String type,
                                                @RequestParam("signStatus") String signStatus) {
        return ADOConnection.runTask(getCurrDs(), experimentExecuteService, "electronicSignatureCallback", Response.class, experimentEquipmentId, documentId, tenantName, contact, type, signStatus);
    }

}
